package edu.ccut.saturn.studio.database.preferences;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnDialogUtil;
import edu.ccut.saturn.studio.database.model.DBConnection;
import edu.ccut.saturn.studio.database.model.DBConnectionProvider;
import edu.ccut.saturn.studio.database.ui.DBConnectView;
import edu.ccut.saturn.studio.database.ui.ManageConnectionDialog;
import edu.ccut.saturn.studio.database.ui.ViewerDBConContentProvider;

/**
 * 连接配置管理界面
 * 
 * @author 谷钰
 * @version 1.0 2008.12.06
 * 
 */
public class DBConnectionPreferencePage extends FieldEditorPreferencePage
		implements IWorkbenchPreferencePage {

	public static final String P_PATH = "pathPreference"; //$NON-NLS-1$
	public static final String P_BOOLEAN = "booleanPreference"; //$NON-NLS-1$
	public static final String P_CHOICE = "choicePreference"; //$NON-NLS-1$
	public static final String P_STRING = "stringPreference"; //$NON-NLS-1$
	private Group infoGroup;
	private Composite client;
	private ComboViewer comboViewer;
	private ViewerDBConContentProvider vcp;
	private Button editBtn;
	private Button delBtn;
	private Button newBtn;
	private StringFieldEditor usr;
	private StringFieldEditor pwd;
	private StringFieldEditor url;
	private StringFieldEditor driverPath;
	private StringFieldEditor driverClass;
	private DBConnection currentConnection;

	public DBConnectionPreferencePage() {
		super(GRID);
		initialize();
	}

	public DBConnectionPreferencePage(DBConnection dbconnection) {
		this();
		currentConnection = dbconnection;
	}

	public void init(IWorkbench iworkbench) {
	}

	protected void initialize() {
		noDefaultAndApplyButton();
		setTitle(Messages.getString("DBConnectionPreferencePage.title")); //$NON-NLS-1$
		setDescription(Messages.getString("DBConnectionPreferencePage.description")); //$NON-NLS-1$
	}

	public Composite getFieldEditorParent() {
		return client;
	}
	
	public Control createContents(Composite composite) {
		client = new Composite(composite, 0);
		vcp = new ViewerDBConContentProvider();

		GridLayout gridlayout = new GridLayout();
		gridlayout.numColumns = 1;
		gridlayout.marginHeight = 0;
		gridlayout.marginWidth = 0;
		client.setLayout(gridlayout);
		client.setFont(composite.getFont());
		client.setLayoutData(new GridData(1808));
		Composite composite1 = new Composite(client, 0);
		composite1.setLayout(new GridLayout(2, false));
		composite1.setLayoutData(new GridData(768));
		Label label = new Label(composite1, 0);
		label.setText(Messages.getString("DBConnectionPreferencePage.databaselinklist")); //$NON-NLS-1$
		comboViewer = new ComboViewer(composite1, 65544);
		comboViewer.getCombo().setLayoutData(new GridData(768));
		comboViewer.setContentProvider(vcp);
		comboViewer.add(vcp.getElements(null));
		comboViewer
				.addSelectionChangedListener(new ISelectionChangedListener() {
					public void selectionChanged(
							SelectionChangedEvent selectionchangedevent) {
						Object selected = ((IStructuredSelection) selectionchangedevent
								.getSelection()).getFirstElement();

						if (selected instanceof DBConnection) {
							update((DBConnection) selected);
						}
					}
				});
		createFieldEditors();
		Composite composite2 = new Composite(client, 0);
		composite2.setLayout(new GridLayout(3, false));
		composite2.setLayoutData(new GridData(40));
		newBtn = new Button(composite2, 8);
		newBtn.setText(Messages.getString("DBConnectionPreferencePage.create")); //$NON-NLS-1$
		setButtonLayoutData(newBtn);
		newBtn.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent selectionevent) {
				ManageConnectionDialog manageconnectiondialog = new ManageConnectionDialog(
						getShell(), null);

				if (manageconnectiondialog.open() == IDialogConstants.OK_ID) {
					currentConnection = null;
					refreshConnectionField();
				}
			}

		});
		editBtn = new Button(composite2, 8);
		editBtn.setText(Messages.getString("DBConnectionPreferencePage.config")); //$NON-NLS-1$
		editBtn.setEnabled(false);
		setButtonLayoutData(editBtn);
		editBtn.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent selectionevent) {
				Object obj = ((IStructuredSelection) comboViewer.getSelection())
						.getFirstElement();

				if (obj instanceof DBConnection) {
					DBConnection connection = (DBConnection) obj;

					ManageConnectionDialog manageconnectiondialog = new ManageConnectionDialog(
							getShell(), connection);

					if (manageconnectiondialog.open() == IDialogConstants.OK_ID) {
						currentConnection = connection;
						refreshConnectionField();
					}
				}
			}

		});
		delBtn = new Button(composite2, 8);
		delBtn.setText(Messages.getString("DBConnectionPreferencePage.delete")); //$NON-NLS-1$
		delBtn.setEnabled(false);
		setButtonLayoutData(delBtn);
		delBtn.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent selectionevent) {
				Object obj = ((IStructuredSelection) comboViewer.getSelection())
						.getFirstElement();
				if ((obj instanceof DBConnection)
						&& SaturnDialogUtil
								.openConfirm(
										getShell(),
										Messages
												.getString("DBConnectionPreferencePage.deletelink"), //$NON-NLS-1$
										Messages
												.getString("DBConnectionPreferencePage.confirmdeletelink"))) { //$NON-NLS-1$
					try {
						DBConnection connection = (DBConnection) obj;

						DBConnectionProvider.getInstance().removeDBConnection(
								connection);
						DBConnectView.getInstance().removeDbConnection(
								connection);

						currentConnection = null;
						refreshConnectionField();
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}

		});

		if (currentConnection == null) {
			Object connections[] = vcp.getElements(null);

			if (connections != null && connections.length > 0) {
				currentConnection = (DBConnection) connections[0];
			}
			return client;
		}
		comboViewer.setSelection(new StructuredSelection(currentConnection));

		return client;
	}

	protected void refreshConnectionField() {
		comboViewer.getCombo().removeAll();

		Object[] elements = vcp.getElements(null);

		comboViewer.add(elements);

		if (currentConnection == null) {
			if (elements != null && elements.length > 0) {
				currentConnection = (DBConnection) elements[elements.length - 1];
			}
		}

		if (currentConnection != null) {
			comboViewer
					.setSelection(new StructuredSelection(currentConnection));
		} else {
			editBtn.setEnabled(false);
			delBtn.setEnabled(false);
		}
	}

	protected void createFieldEditors() {
		infoGroup = new Group(getFieldEditorParent(), 0);
		GridLayout gridlayout = new GridLayout(2, false);
		gridlayout.marginLeft = 10;
		infoGroup.setLayout(gridlayout);
		infoGroup.setLayoutData(new GridData(768));
		infoGroup.setText(Messages.getString("DBConnectionPreferencePage.configmessage")); //$NON-NLS-1$
		driverPath = new StringFieldEditor(P_STRING, Messages
				.getString("DBConnectionPreferencePage.jdbcdriverurl"), infoGroup); //$NON-NLS-1$
		driverPath.fillIntoGrid(infoGroup, 2);
		driverClass = new StringFieldEditor(P_STRING, Messages
				.getString("DBConnectionPreferencePage.driverclassname"), infoGroup); //$NON-NLS-1$
		driverClass.fillIntoGrid(infoGroup, 2);
		url = new StringFieldEditor(P_STRING, Messages
				.getString("DBConnectionPreferencePage.ruladdress"), infoGroup); //$NON-NLS-1$
		url.fillIntoGrid(infoGroup, 2);
		usr = new StringFieldEditor(P_STRING, Messages
				.getString("DBConnectionPreferencePage.username"), infoGroup); //$NON-NLS-1$
		usr.fillIntoGrid(infoGroup, 2);
		pwd = new StringFieldEditor(P_STRING, Messages
				.getString("DBConnectionPreferencePage.password"), infoGroup); //$NON-NLS-1$
		pwd.getTextControl(infoGroup).setEchoChar('*');
		pwd.fillIntoGrid(infoGroup, 2);
		addField(driverPath);
		driverPath.getTextControl(infoGroup).setEditable(false);
		addField(driverClass);
		driverClass.getTextControl(infoGroup).setEditable(false);
		addField(url);
		url.getTextControl(infoGroup).setEditable(false);
		addField(usr);
		usr.getTextControl(infoGroup).setEditable(false);
		addField(pwd);
		pwd.getTextControl(infoGroup).setEditable(false);
	}

	protected void update(DBConnection dbconnection) {
		usr.getTextControl(infoGroup).setText(dbconnection.getUsername());
		pwd.getTextControl(infoGroup).setText(dbconnection.getPassword());
		url.getTextControl(infoGroup).setText(dbconnection.getUrl());
		driverPath.getTextControl(infoGroup).setText(
				dbconnection.getDriverPath());
		driverClass.getTextControl(infoGroup).setText(
				dbconnection.getDriverClassName());

		editBtn.setEnabled(true);
		delBtn.setEnabled(true);
	}
}
